const api = require('./../../config/api');
const request = require('./../../utils/request');
const { getTodayDate } = require('./../../utils/util');
const app = getApp();
const env = __wxConfig.envVersion;
const { echarts } = requirePlugin('echarts');
import lottie from '../../utils/lottie';
Page({
  data: {
    articleList: [],
    patientInfo: '',
    patientList: '',
    isChart: false,
    showReportModal: false,
    reportData: [],
    currentSceneList: [], // 当前孩子所加入场景训练列表
    vacantSceneTaskList: [], // 空缺任务列表
    vancantSceneNum: 0, // 空缺任务数量
    sceneTaskList: [], // 今日场景训练任务列表
    sceneList: [], // 场景训练任务前3
    hadLogin: app.isLogin(),
    optionList: [], // 评估效果列表
    // 轮播图数据
    bannerList: [],
    activityDialogShow: false, // 活动弹窗
    activityData: {}, // 活动弹窗数据
    env: env,
    // 金刚区图标
    iconList: [
      {
        name: '学习认知',
        icon: 'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backendc23f2389b364405988d79a9ad2f6eee5.png',
        path: '/pages/learningCognition/index',
      },
      {
        name: '趣味感统',
        icon: 'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend7eb33ddde2d54a8d812ff3cdc1a63b19.png',
        path: '/pages/interestSentiment/index',
      },
      {
        name: '成长日记',
        icon: 'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend51310ab37cc64b51b8d7b4bae3b0ab6d.png',
        path: '/pages/diary/index',
      },
      {
        name: '自我评估',
        icon: 'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend2013f10082854975b35edf7eb968f586.png',
        path: '/pages/selfAssessment/index',
      },
      {
        name: '育儿咨询',
        icon: 'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend771e69a4c5c0496386151ba4f1560fdf.png',
        path: '/pages/consultationOnline/index',
      },
    ],
    slideWidth: '', //滑块宽
    slideLeft: 0, //滑块位置
    totalLength: '', //当前滚动列表总长
    slideShow: false,
    slideRatio: '',
    defaultBannerList: [
      {
        id: '',
        activityId: '',
        bannerTitle: '趣味感统',
        bannerUrl:
          'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend099a0a2f192f49a7bf88651ec3dfdaf3.png',
        activityInfo: {
          id: '',
          activityTitle: '',
          appletRoute: '/pages/interestSentiment/index',
        },
      },
      {
        id: '',
        activityId: '',
        bannerTitle: '学习认知',
        bannerUrl:
          'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend7a77fc17a6ea48569cea4706fcfb23ae.png',
        activityInfo: {
          id: '',
          activityTitle: '',
          appletRoute: '/pages/learningCognition/index',
        },
      },
      // {
      //   id: '',
      //   activityId: '',
      //   bannerTitle: '学习认知',
      //   bannerUrl:
      //     'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zl-backend13b1e673eab6466abbc21a5533424400.png',
      //   activityInfo: {
      //     id: '',
      //     activityTitle: '',
      //     appletRoute: '/pages/learningCognition/index',
      //   },
      // },
    ],
  },
  // 查看更多文章
  more() {
    wx.navigateTo({
      url: '../articleList/index',
    });
  },
  // 跳转文章详情
  articleDetial(val) {
    const item = val.currentTarget.dataset.item;
    if (item?.id) {
      wx.navigateTo({
        url: '../articleDetail/index?id=' + item.id,
      });
    }
  },
  onShow() {
    wx.setNavigationBarTitle({
      title: '可知成长',
    });
    this.hadNavigate = false;
    this.hadNavigateToPage = false;
    this.dialogShow = false;
    // 获取轮播图列表
    this.getBannerList();

    const { year, month, day } = getTodayDate();
    this.setData({
      today: year + '-' + month + '-' + day,
      hadLogin: app.isLogin(),
      optionList: [],
      reportData: [],
      articleList: [],
      slideLeft: 0,
    });
    if (app.isLogin()) {
      this.getActivityData();
    }
    // 获取推荐文章列表
    this.getArticleList();
    if (app.isLogin()) {
      this.getPatientList();
    }
    this.getMostTrain();
    let patientInfo = wx.getStorageSync('patientInfo');

    if (patientInfo) {
      if (!patientInfo?.age) {
        let ageObj = { age: patientInfo.monthAgeStr };
        patientInfo = Object.assign(patientInfo, ageObj);
        wx.setStorageSync('patientInfo', patientInfo);
      }
      this.setData({
        patientInfo,
      });
      const { id } = patientInfo;
      // 评估效果
      this.getRecordList(id);
      // 当前患者绑定场景训练
      this.getCurrentTrainList(id);
      // 当前患者空缺任务
      this.getVacantSceneList(id);
      // 当前患者今日场景训练任务
      this.getTodaySceneList(id);
      // 当前患者评估结果列表
      this.getTrainReportList(id);
    } else {
      this.setData({
        patientInfo: '',
        optionList: [],
      });
    }
  },
  onLoad(query) {
    // 获取弹窗信息
    if (!app.isLogin()) {
      this.getActivityData();
    }

    // 初始化摇一摇动效
    this.initAnimation();

    var self = this;
    var systemInfo = wx.getSystemInfoSync();
    self.setData({
      windowHeight:
        app.globalData.navigate_type == 1
          ? systemInfo.windowHeight
          : systemInfo.windowHeight - 35,
      windowWidth: systemInfo.windowWidth,
      navigate_type: app.globalData.navigate_type,
    });

    console.log('query--------', query);
    // 1.通过分享链接、渠道链接
    if (query?.activityId) {
      // 个人分享
      if (query?.userId) {
        wx.setStorageSync('invite_user_id', query?.userId);
        console.log('邀请人数据--用户：', query?.userId);
      }
      // 渠道分享
      if (query?.channelKey) {
        wx.setStorageSync('invite_channel', query?.channelKey);
        console.log('邀请人数据--渠道：', query?.channelKey);
      }
      if (query?.fromShare) {
        //去统计--------
        this.handleStatic();
      }
      this.getActivityDetail(query?.activityId);
    }
    // 2.通过分享二维码、渠道二维码进入首页
    const scene = decodeURIComponent(query?.scene);
    console.log('scene--------', scene);
    if (scene === 'undefined') {
      return;
    }
    let activityIdParams = scene?.split('&')[0];
    let channelKeyParams = scene?.split('&')[1];
    let activityId = '';
    let channelKey = '';
    let userId = '';

    if (activityIdParams) {
      let activityArr = activityIdParams?.split('=');
      let channelKeyArr = channelKeyParams?.split('=');
      if (activityArr[0] === 'activityId') {
        activityId = activityArr[1];
      }
      if (channelKeyArr[0] === 'channelKey') {
        channelKey = channelKeyArr[1];
        wx.setStorageSync('invite_channel', channelKey);
      }
      if (channelKeyArr[0] === 'userId') {
        userId = channelKeyArr[1];
        wx.setStorageSync('invite_user_id', userId);
      }
      this.getActivityDetail(activityId);
    }
  },
  // 初始化加载动画
  initAnimation() {
    if (this.init) {
      return;
    }
    wx.createSelectorQuery()
      .selectAll('#activity_lott')
      .node((res) => {
        const canvas = res[0].node;
        const context = canvas.getContext('2d');
        canvas.width = 750;
        canvas.height = 1624;
        lottie.setup(canvas);
        this.ani = lottie.loadAnimation({
          loop: true,
          autoplay: true,
          animationData: require('./data.js'),
          rendererSettings: {
            context,
          },
        });
        this.init = true;
      })
      .exec();
  },
  // 统计点击分享卡片
  async handleStatic() {
    const appletUserId = wx.getStorageSync('userId') || '';
    const res = await request.get(
      api.shareCount,
      { eventFlag: 'practiceAward', appletUserId },
      { loading: false }
    );
    if (res.httpStatus === 200) {
      console.log('统计成功');
    }
  },
  //根据分类获取比例
  getRatio() {
    let { optionList, windowWidth } = this.data;
    if (optionList.length <= 1) {
      this.setData({
        slideShow: false,
      });
    } else {
      var totalLength = optionList.length * 620; //分类列表总长度
      var ratio = (82 / totalLength) * (750 / windowWidth); //滚动列表长度与滑条长度比例
      var showLength = (750 / totalLength) * 82; //当前显示红色滑条的长度(保留两位小数)
      this.setData({
        slideWidth: showLength,
        totalLength: totalLength,
        slideShow: true,
        slideRatio: ratio,
      });
    }
  },
  //slideLeft动态变化
  getLeft(e) {
    this.setData({
      slideLeft: e.detail.scrollLeft * this.data.slideRatio,
    });
  },
  // 获取活动详情
  async getActivityDetail(activityId) {
    const res = await request.get(
      api.activityDetail,
      {
        activityId: activityId,
      },
      { loading: false }
    );
    if (res.httpStatus === 200) {
      let info = res.data;
      if (info.appletRoute !== '/pages/index/index') {
        wx.navigateTo({
          url: `${info.appletRoute}?activityId=${activityId}`,
        });
      }
    }
  },
  // 获取患者列表
  getPatientList: async function () {
    const userId = wx.getStorageSync('userId');
    const res = await request.get(
      api.getPatientList + '/' + userId,
      {},
      { loading: false }
    );

    if (res.httpStatus === 200) {
      if (res.data.length > 0) {
        for (const item of res.data) {
          item.age = item.monthAgeStr;
        }
        const index = res.data.findIndex((value) => value.isDefault === 1);
        if (index !== -1 && !res.data[index]?.age) {
          res.data[index].age = res.data[index].monthAgeStr;
          wx.setStorageSync('patientInfo', res.data[index]);
        }
        this.setData({
          patientInfo: res.data[index],
          patientList: res.data,
        });
      } else {
      }
    }
  },
  // 当前孩子所绑定的场景训练
  async getCurrentTrainList(patientId) {
    const res = await request.get(
      api.patientTraining + patientId,
      {},
      { loading: false }
    );
    if (res.httpStatus === 200) {
      this.setData({
        currentSceneList: res.data,
      });
    }
  },
  // 评估效果
  async getRecordList(patientId) {
    const res = await request.get(
      api.getEvaluationEffect,
      { patientId },
      { loading: false }
    );
    if (res.httpStatus === 200) {
      let optionList = [];
      res.data.map((obj) => {
        this.getChartData(obj, optionList);
      });
      this.setData({
        optionList,
      });
      //计算比例
      this.getRatio();
    }
  },
  getChartData: function (obj, optionList) {
    let info = wx.getSystemInfoSync().system;
    let isios = info.indexOf('ios') != -1;

    let list = obj.dayDetailList;
    const Ydata = list.map((obj) => {
      return obj.score;
    });
    const Xdata = list.map((obj) => {
      return obj.taskTime.substring(5, 10);
    });

    const option = {
      grid: {
        left: isios ? '12%' : '10%',
        right: isios ? '12%' : '10%',
        height: '75%',
        top: 10,
        bottom: 5,
      },
      xAxis: {
        boundaryGap: false,
        axisLabel: {
          showMaxLabel: true,
          color: '#5D5C5D',
        },
        axisLine: {
          lineStyle: {
            color: '#bebebe',
            type: 'dashed',
          },
        },
        data: Xdata,
      },
      yAxis: {
        splitLine: {
          show: true,
          lineStyle: {
            type: 'dashed',
            color: '#bebebe',
          },
        },
        axisLabel: {
          showMaxLabel: true,
          color: '#5D5C5D',
        },
      },
      series: [
        {
          data: Ydata,
          type: 'line',
          smooth: true,
          symbolSize: 0,
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 1, 0, 0, [
              {
                offset: 1,
                color: 'rgba(0,203,106,0.60)',
              },
              {
                offset: 0,
                color: 'rgba(0,203,106,0.10)',
              },
            ]),
          },
          itemStyle: {
            normal: {
              color: '#00CB6A', //改变折线点的颜色
              borderWidth: 0,
              lineStyle: {
                color: '#00CB6A', //改变折线颜色
              },
            },
          },
        },
      ],
      tooltip: {
        trigger: 'axis',
        borderColor: '#efbe24',
        backgroundColor: '#efbe24',
        formatter: '{c0}分',
        textStyle: {
          color: '#fff',
          fontSize: '18',
        },
        padding: [5, 5, 5, 5],
      },
    };

    this.setData({
      option: option,
    });

    let item = {
      questionnaireName: obj.questionnaireName,
      option: option,
    };
    optionList.push(item);
  },
  // 金刚区跳转
  handleToIcon(e) {
    let patientInfo = wx.getStorageSync('patientInfo');
    let { id } = patientInfo;
    let { hadLogin } = this.data;
    let url = e.currentTarget.dataset.url;
    let index = e.currentTarget.dataset.index;
    if (index === 2) {
      if (id) {
        wx.navigateTo({
          url: url,
        });
      } else {
        if (!hadLogin) {
          app.navTo(url);
        } else {
          app.globalData.createPatientEntrance = 7;
          wx.navigateTo({
            url: '/pages/createPatient/select/select',
          });
        }
      }
    } else if (index === 3 || index === 4) {
      app.navTo(url);
    } else {
      wx.navigateTo({
        url: url,
      });
    }
  },

  // 登录
  async login(e) {
    const url = e.currentTarget.dataset.url;
    app.navTo(url);
  },
  // 点击去绑定
  handleBind() {
    app.globalData.createPatientEntrance = 4;
    let url = '/pages/createPatient/select/select';
    app.navTo(url);
  },
  // 获取文章列表
  getArticleList: async function (id) {
    const res = await request.get(
      api.getHotArticleList,
      {},
      { loading: false }
    );
    if (res.httpStatus === 200) {
      this.setData({
        articleList: res.data,
      });
    }
  },
  // 点击切换患者
  changeBtn() {
    this.setData({
      showModalStatus: true,
    });
  },
  // 切换患者
  patientChange: function (e) {
    this.setData({
      patientInfo: e.detail,
      showModalStatus: false,
      isChart: false,
      optionList: [],
      reportData: [],
    });
    this.getRecordList(e.detail.id);
    this.getCurrentTrainList(e.detail.id);
    this.getVacantSceneList(e.detail.id);
    this.getTodaySceneList(e.detail.id);
    this.getTrainReportList(e.detail.id);
    this.getPatientList();
  },
  modelChange: function (e) {
    this.setData({
      showModalStatus: e.detail,
    });
  },
  // 点击全部训练
  handleAllScene() {
    wx.navigateTo({
      url: '/pages/myCollection/index?source=1',
    });
  },
  // 点击跳转场景训练详情
  handleSceneDetail(e) {
    let trainingId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/sceneDetail/index?trainingId=' + trainingId,
    });
  },
  // 点击跳转训练模版详情
  handleSceneTrainDetail(e) {
    let trainingId = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/sceneTrainDetail/index?trainingId=' + trainingId,
    });
  },
  // 点击跳转训练任务详情
  handleSceneTaskDetail(e) {
    let {
      trainingId,
      detailId,
      questionnaireId,
      trainingType,
      state,
      recordId,
    } = e.currentTarget.dataset.item;
    let taskType = e.currentTarget.dataset.type;

    if (taskType === 'vacancy') {
      app.globalData.finishTaskEntrance = 2;
      app.globalData.isVacancyIndex = 1;
    } else {
      app.globalData.finishTaskEntrance = 1;
    }

    if (Number(trainingType) === 1) {
      wx.navigateTo({
        url: '/pages/sceneTaskDetail/index?id=' + detailId,
      });
    } else {
      if (state === 4) {
        wx.navigateTo({
          url: `/pages/selfAssessment/question/result?id=${recordId}&pathId=${trainingId}`,
        });
        return;
      }
      wx.navigateTo({
        url:
          '/pages/selfAssessment/question/index?key=1&id=' +
          questionnaireId +
          '&pathId=' +
          trainingId +
          '&taskFlowId=' +
          detailId,
      });
    }
  },
  // 查看更多空缺任务
  handleVacancy() {
    if (this.data.vancantSceneNum > 3) {
      wx.navigateTo({
        url: '/pages/practiceVacancy/index',
      });
    } else {
      wx.showToast({
        title: '无更多空缺',
        icon: 'none',
      });
    }
  },
  // 展示绑定人次最多的场景训练模板
  async getMostTrain() {
    const res = await request.get(api.mostTraining, {}, { loading: false });
    if (res.httpStatus === 200) {
      let list = res.data;
      var result = [];
      for (var i = 0; i < list.length; i += 3) {
        result.push(list.slice(i, i + 3));
      }
      this.setData({
        sceneList: result,
      });
    }
  },
  // 获取当前孩子空缺训练列表
  async getVacantSceneList(patientid) {
    let that = this;
    const res = await request.get(
      api.vacanciesTraining + patientid,
      {},
      { loading: false }
    );

    if (res.httpStatus === 200) {
      res.data.forEach((item) => {
        item.startDate = item.startDate.split(' ')[0];
      });
      that.setData({
        vancantSceneNum: res.data.length,
        vacantSceneTaskList: res.data.splice(0, 3),
      });
    }
  },
  // 获取当前孩子今天场景训练任务列表
  async getTodaySceneList(patientId) {
    const res = await request.get(
      api.todayTraining + patientId,
      {},
      { loading: false }
    );
    if (res.httpStatus === 200) {
      this.setData({
        sceneTaskList: res.data,
      });
    }
  },
  onUnload: function () {
    app.globalData.indexUrl = false;
  },
  // 关闭场景训练报告弹窗
  onCloseModal: function () {
    this.setData({
      showReportModal: false,
    });
  },
  // 获取患者训练报告
  getTrainReportList: async function (id) {
    const res = await request.get(
      api.getPatientTrainReport,
      { patientId: id },
      { loading: false }
    );
    if (res.data.length > 0) {
      this.setData({
        // showReportModal:true,
        reportData: res.data,
      });
    }
  },
  // 点击跳转孩子详情
  handleDetail() {
    let { id, isDefault, isBindOne } = this.data.patientInfo;
    wx.navigateTo({
      url:
        '/pages/patientDetail/index?id=' +
        id +
        '&isDefault=' +
        isDefault +
        '&isBindOne=' +
        isBindOne,
    });
  },
  // 点击治疗日记
  handleDiary() {
    const url = '/pages/diary/index';
    const patientInfo = wx.getStorageSync('patientInfo');
    const { id } = patientInfo;
    let { hadLogin } = this.data;
    if (id) {
      wx.navigateTo({
        url: url,
      });
    } else {
      if (!hadLogin) {
        app.navTo(url);
      } else {
        app.globalData.createPatientEntrance = 7;
        wx.navigateTo({
          url: '/pages/createPatient/select/select',
        });
      }
    }
  },
  // 跳转评估效果展示设置
  handleSetting() {
    wx.navigateTo({
      url: '/pages/evaluatedEffect/index',
    });
  },
  // 获取轮播图列表
  async getBannerList() {
    let { defaultBannerList } = this.data;
    // 单独写死执行能力评估
    let evaluation = {
      activityId: 'zxnlpg',
      bannerTitle: '执行能力评估',
      bannerType: true,
      bannerUrl:
        'https://kj-zhiliao.oss-cn-qingdao.aliyuncs.com/zhiliao-applet/iL5LwhFiWTt518ca9f45be41d079a59d91e5c787d59e.png',
    };
    const res = await request.get(api.bannerList, {}, { loading: false });
    if (res.httpStatus === 200) {
      let bannerArr = [];
      if (res.data.length > 0) {
        bannerArr = res.data;
        if (bannerArr.length > 0 && bannerArr.length < 3) {
          if (bannerArr.length === 1) {
            let arr1 = [evaluation, bannerArr[0], evaluation];
            bannerArr = [...bannerArr, ...arr1];
          } else {
            bannerArr.push(evaluation);
          }
        } else {
          bannerArr.push(evaluation);
        }
      } else {
        bannerArr = defaultBannerList.concat(evaluation);
      }

      this.setData({
        bannerList: bannerArr,
      });
    }
  },
  // 获取活动弹窗信息
  async getActivityData() {
    const res = await request.get(api.getPopUp, {}, { loading: false });
    if (res.httpStatus === 200) {
      let needPopUp = res.data.needPopUp;
      this.setData({
        activityData: res.data,
        activityDialogShow: needPopUp === 1,
      });
      this.dialogShow = needPopUp === 1;
      if (needPopUp === 0) {
        setTimeout(() => {
          let { reportData } = this.data;
          this.setData({
            showReportModal: reportData.length > 0 ? true : false,
          });
        }, 1000);
      } else {
        this.handleShake();
      }
    }
  },
  // 关闭活动弹窗
  handleCloseActivity() {
    let { reportData } = this.data;
    let isShow = false;
    if (reportData.length > 0) {
      isShow = true;
    }
    this.setData({
      activityDialogShow: false,
      showReportModal: isShow,
    });
    this.dialogShow = false;
  },
  // 轮播图跳转
  async jumpBannerPath(e) {
    let activityId = e.currentTarget?.dataset?.id;
    let { hadLogin, patientInfo } = this.data;

    // 执行能力评估
    if (activityId === 'zxnlpg') {
      // 已登录
      if (hadLogin && patientInfo) {
        let res = await request.get(
          api.getEvaluationResult,
          {},
          { loading: false }
        );
        // 有评估结果---进入评估结果页
        if (res.data?.patientRecord) {
          wx.navigateTo({
            url: '/pages/activity/evaluationResult/index',
          });
        } else {
          // 没评估结果---进入评估说明页
          wx.navigateTo({
            url: '/pages/activity/evaluationDescription/index',
          });
        }
      } else {
        // 未登录---进入评估说明页
        wx.navigateTo({
          url: '/pages/activity/evaluationDescription/index',
        });
      }
    }

    let path = e.currentTarget?.dataset?.path;
    if (!path) return;
    if (!activityId) {
      wx.navigateTo({
        url: path,
      });
    } else {
      if (path !== '/pages/index/index') {
        wx.navigateTo({
          url: `${path}?activityId=${activityId}`,
        });
      }
    }
  },
  // 点击活动弹窗进入活动页
  handleToActivity() {
    let { activityId, appletRoute } = this.data.activityData;
    this.handleCloseActivity();
    if (appletRoute !== '/pages/index/index') {
      wx.navigateTo({
        url: `${appletRoute}?activityId=${activityId}`,
      });
    }
  },
  // 摇一摇
  handleShake() {
    let that = this;
    wx.startAccelerometer({
      interval: 'game',
    });
    wx.onAccelerometerChange(function (e) {
      let page = getCurrentPages();
      let currentPage = page[page.length - 1];
      // 添加限制，防止重复跳转
      if (
        currentPage.route === 'pages/index/index' &&
        that.dialogShow &&
        !that.hadNavigate &&
        !that.hadNavigateToPage
      ) {
        if (e.x > 0.1 && e.y > 0.1) {
          wx.vibrateShort({
            type: 'heavy',
          });
          // wx.showToast({
          //   title: '摇一摇成功',
          //   icon: 'success',
          //   duration: 2000
          // })
          that.hadNavigate = true;
          setTimeout(() => {
            that.handleToActivity();
            wx.offAccelerometerChange(() => {
              console.log('取消监听');
            });
            that.hadNavigateToPage = true;
          }, 1000);
        }
      }
    });
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  onTabItemTap(item) {
    wx.vibrateShort({
      type: 'light',
    });
  },
});
